package com.itheima.servcie;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itheima.bean.CodeBean;
import com.itheima.dbservice.*;
import com.itheima.dto.AnswerDto;
import com.itheima.pojo.*;
import com.itheima.utils.OptionScoreUtil;
import com.itheima.vo.*;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TestSoulService {
    @DubboReference
    private SoulQuestiontypeApi soulQuestiontypeApi;
    @DubboReference
    private SoulQuestionServiceApi soulQuestionServiceApi;
    @DubboReference
    private SoulQuestionchoiceServiceApi soulQuestionchoiceServiceApi;
    @DubboReference
    private ReportServiceApi reportServiceApi;
    @DubboReference
    private SimilarYouServiceApi similarYouServiceApi;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;
    @DubboReference
    private SoulScoreServiceApi soulScoreServiceApi;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public Object[] getQuestions() {
        String uid = stringRedisTemplate.opsForValue().get(CodeBean.ID);
        if (ObjectUtil.isNotNull(stringRedisTemplate.opsForValue().get(CodeBean.QUESTION_TYPE + uid))) {
            String type = stringRedisTemplate.opsForValue().get(CodeBean.QUESTION_TYPE + uid);
            if (Convert.toInt(type) > 3){
                stringRedisTemplate.delete(CodeBean.QUESTION_TYPE + uid);
            }
        }
        //查询所有套题
        List<SoulQuestiontype> soulQuestiontypes = soulQuestiontypeApi.getAll();
        //对每份套题进行数据处理和封装
        List<SoulQuestionResult> resultList = new ArrayList<>();
        for (SoulQuestiontype soulQuestiontype : soulQuestiontypes) {
            //测试
//            soulQuestiontype.setReportId(null);
            //查找对应问题
            List<SoulQuestion> soulQuestions = soulQuestionServiceApi.getQuestionsByQuestiontypeId(soulQuestiontype.getId());
            //查找每个问题对应选项
            List<Questions> questionsList = new ArrayList<>();
            for (SoulQuestion soulQuestion : soulQuestions) {
                //封装questions集合
                List<SoulQuestionchoice> soulQuestionchoices = soulQuestionchoiceServiceApi.getQuestionchoiceById(soulQuestion.getId());
                Questions questions = new Questions();
                questions.setId(soulQuestion.getId());
                questions.setQuestion(soulQuestion.getQuestion());
                //封装option
                List<Options> optionsList = new ArrayList<>();
                for (SoulQuestionchoice soulQuestionchoice : soulQuestionchoices) {
                    getOptionsList(soulQuestion, optionsList, soulQuestionchoice);
                }
                questions.setOptions(ArrayUtil.toArray(optionsList, Options.class));
                questionsList.add(questions);
            }
            //封装SoulQuestionResult
            SoulQuestionResult soulQuestionResult = new SoulQuestionResult();
            BeanUtil.copyProperties(soulQuestiontype, soulQuestionResult);
            soulQuestionResult.setQuestions(ArrayUtil.toArray(questionsList, Questions.class));

            resultList.add(soulQuestionResult);
        }
        //redis存储答题题号
        if (ObjectUtil.isNull(stringRedisTemplate.opsForValue().get(CodeBean.QUESTION_TYPE + uid))) {
            stringRedisTemplate.opsForValue().set(CodeBean.QUESTION_TYPE + uid, "1");
        }else {
            stringRedisTemplate.opsForValue().set(CodeBean.QUESTION_TYPE + uid, String.valueOf(stringRedisTemplate.opsForValue().get(CodeBean.QUESTION_TYPE + uid)) + 1);
        }
        return resultList.toArray();
    }

    private void getOptionsList(SoulQuestion soulQuestion, List<Options> optionsList, SoulQuestionchoice soulQuestionchoice) {
        {Options options = new Options();
            options.setId("A");
            options.setOption(soulQuestionchoice.getA());
            optionsList.add(options);}

        {Options options = new Options();
            options.setId("B");
            options.setOption(soulQuestionchoice.getB());
            optionsList.add(options);}

        {if (ObjectUtil.isNull(soulQuestionchoice.getC())){
            return;
        }
            Options options = new Options();
            options.setId("C");
            options.setOption(soulQuestionchoice.getC());
            optionsList.add(options);}

        {if (ObjectUtil.isNull(soulQuestionchoice.getD())){
            return;
        }
        Options options = new Options();
            options.setId("D");
            options.setOption(soulQuestionchoice.getD());
            optionsList.add(options);}
        {if (ObjectUtil.isNull(soulQuestionchoice.getE())){
            return;
        }
            Options options = new Options();
            options.setId("E");
            options.setOption(soulQuestionchoice.getE());
            optionsList.add(options);}
        {if (ObjectUtil.isNull(soulQuestionchoice.getF())){
            return;
        }
            Options options = new Options();
            options.setId("F");
            options.setOption(soulQuestionchoice.getF());
            optionsList.add(options);}
        {if (ObjectUtil.isNull(soulQuestionchoice.getG())){
            return;
        }
            Options options = new Options();
            options.setId("G");
            options.setOption(soulQuestionchoice.getG());
            optionsList.add(options);}
    }

    public String answers(List<AnswerDto> answers) {
        Integer score = 0;
        //获取总分
        for (Object answer : answers) {
            // 解析
            String jsonObject = JSON.toJSONString(answer);
            AnswerDto answerDto = JSONObject.parseObject(jsonObject, AnswerDto.class);

            score += getScore(answerDto.getQuestionId(), answerDto.getOptionId());
            //假数据测试
//            score += getScore("1","1");
        }
        //进行分数字段匹配返回msg的id
        Integer reportId = OptionScoreUtil.getMsgId(score);
        //取出当前题号
        Integer id = Convert.toInt(stringRedisTemplate.opsForValue().get(CodeBean.QUESTION_TYPE + 1));
        //将reportId存入
        soulQuestiontypeApi.updateReportId(id, reportId);
        //解锁下一题
        if ((id + 1) <= 3){
            soulQuestiontypeApi.updateIsLock(id + 1);
        }
        return Convert.toStr(reportId);
    }

    /**
     * 获取单个选项分数
     * @param questionId
     * @param optionId
     * @return
     */
    public Integer getScore(String questionId, String optionId){
        //获取对应id的options分数集合
        SoulScore scorelist = soulScoreServiceApi.getById(questionId);
        //进行选项匹配
        switch (optionId) {
            case "A":
                return scorelist.getA();
            case "B":
                return scorelist.getB();
            case "C":
                return scorelist.getC();
            case "D":
                return scorelist.getD();
            case "E":
                return scorelist.getE();
            case "F":
                return scorelist.getF();
            case "G":
                return scorelist.getG();
            default:
                return 0;
        }
    }

    public ReportVo report(Integer id) {
        //当前用户id
        Integer uid = Convert.toInt(stringRedisTemplate.opsForValue().get(CodeBean.ID));
        //查询报告信息
        Report report = reportServiceApi.getById(id);
        //查询相似用户id
        List<SimilarYou> similarYou = similarYouServiceApi.getByUid(uid);
        List<SimUserVo> simUserVoList = new ArrayList<>();
        for (SimilarYou user : similarYou) {
            UserInfo userInfo = userInfoServiceApi.getUserInfoById(Convert.toLong(user.getSimilarId()));
            SimUserVo simUserVo = new SimUserVo();
            simUserVo.setId(Convert.toInt(userInfo.getId()));
            simUserVo.setAvatar(userInfo.getAvatar());
            simUserVoList.add(simUserVo);
        }
        //封装纬度
        List<Map<String, String>> dimensionsList = OptionScoreUtil.getDimensionsList();

        ReportVo reportVo = new ReportVo();
        reportVo.setConclusion(report.getMsg());
        reportVo.setCover(report.getCover());
        reportVo.setSimilarYou(simUserVoList.toArray());
        reportVo.setDimensions(dimensionsList.toArray());
        return reportVo;
    }
}
